package com.ruoyi.system.outto.goods.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.model.domain.*;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.model.mapper.InfoImgMapper;
import com.ruoyi.system.outto.core.*;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.game.IZJYAPI;
import com.ruoyi.system.outto.goods.NEWIZJYAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class NEWZJYAPIImpl implements NEWIZJYAPI {
    @Resource
    private InfoImgMapper infoImgMapper;
    @Resource
    private CommonApi commonApi;
    @Resource
    private GoodsInfoMapper goodsInfoMapper;
    @Resource
    private GameAttributeMapper gameAttributeMapper;
    @Resource
    private ArtRecMapper artRecMapper;
    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;
    @Value("${desc.title}")
    private String descTitle;

    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,SalePartner salePartner) {
        Map<String, Object> params = params(goodsInfoAndAttrValueDto,salePartner);
        String path = "/shopadd";
        //进行排序
        List<Map.Entry<String, Object>> entries = new MapSort().sortMap(params);
        Map<String, Object> map = getSignAndsortMap(entries,salePartner);

        log.info(salePartner.getName()+"新增请求参数={}", JSONObject.toJSONString(map));
        String twoOther = salePartner.getTwoOther();
        log.info(salePartner.getName()+"新增请求地址={}", twoOther);
        String response =   HttpUtils.doPostForm(twoOther+path, map,null);
        log.info(salePartner.getName()+"新增返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        String info = resultJson.getString("info");

        Map<String, Object> result = new HashMap<>();
        if (!"100".equals(resultJson.getString("code"))) {
            result.put("code",500);
        }else {
            result.put("code",200);
            ArtRec artRecreq = new ArtRec();
            artRecreq.setConfig(salePartner.getId());
            artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
            List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
            if(artRecs.size()>0) {
                artRecs.get(0).setOutid(String.valueOf(goodsInfoAndAttrValueDto.getId()));
                artRecMapper.updateArtRec(artRecs.get(0));
            }else{
                artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
                artRecreq.setCreateId(goodsInfoAndAttrValueDto.getCreateId());
                artRecreq.setType(LCConstant.interAdd);
                artRecreq.setConfig(salePartner.getId());
                artRecreq.setSaleCode(salePartner.getSaleName());
                artRecreq.setOutid(String.valueOf(goodsInfoAndAttrValueDto.getId()));
                artRecMapper.insertArtRec(artRecreq);
            }
        }
        result.put("req",JSONObject.toJSONString(params));
        result.put("res",response);
        result.put("msg",info);
        return AjaxResult.success(result);
    }


    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,SalePartner salePartner) {
        Map<String, Object> params = params(goodsInfoAndAttrValueDto,salePartner);
        String path = "/shopedit";
        String paramsStr = JSONObject.toJSONString(params);
        log.info(salePartner.getName()+"编辑请求参数={}", paramsStr);
        //进行排序
        List<Map.Entry<String, Object>> entries = new MapSort().sortMap(params);
        Map<String, Object> map = getSignAndsortMap(entries,salePartner);
        String twoOther = salePartner.getTwoOther();
        String response =   HttpUtils.doPostForm(twoOther + path, map,null);

        log.info(salePartner.getName()+"编辑返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        String info = resultJson.getString("info");

        Map<String, Object> result = new HashMap<>();
        if (!"100".equals(resultJson.getString("code"))) {
            result.put("code",500);
        }else {
            result.put("code",200);
        }

        result.put("req",JSONObject.toJSONString(params));
        result.put("res",response);
        result.put("msg",info);
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,SalePartner salePartner) {


        String path = "/shopcontrol";
        HashMap<String, Object> params = new HashMap<>();
        params.put("shopcode", goodsInfoAndAttrValueDto.getId().toString());
        params.put("type", Integer.valueOf(ZJYConstant.DEL.getValue()));
        params.put("importcode", salePartner.getOther());
        params.put("importid", salePartner.getThreeOther());
        String paramsStr = JSONObject.toJSONString(params);
        log.info(salePartner.getName()+"删除请求参数={}", paramsStr);
        //进行排序
        List<Map.Entry<String, Object>> entries = new MapSort().sortMap(params);
        Map<String, Object> map = getSignAndsortMap(entries,salePartner);
        String twoOther = salePartner.getTwoOther();
        String response = HttpUtils.doPostForm(twoOther + path, map,null);

        log.info(salePartner.getName()+"删除返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        String info = resultJson.getString("info");
        info = MapUntils.unicodeToString(info);

        Map<String, Object> result = new HashMap<>();
        if (!"100".equals(resultJson.getString("code"))) {
            result.put("code",500);
        }else {
            result.put("code",200);
            ArtRec artRecreq = new ArtRec();
            artRecreq.setConfig(salePartner.getId());
            artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
            List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
            if(artRecs.size()>0) {
                artRecMapper.deleteArtRecById(artRecs.get(0).getId());
            }
        }

        result.put("req",JSONObject.toJSONString(params));
        result.put("res",response);
        result.put("msg",info);
        return AjaxResult.success(result);
    }

    private Map<String, Object> params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,SalePartner sa) {

        GameAttribute gameAttribute = null;
        String pfIds = "";
        if(goodsInfoAndAttrValueDto.getGameName().contains("王者荣耀")){
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF16())){
                throw new GlobalException("实名不能为空");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF16()));
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF5());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF9());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF10());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF11());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF12());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF15());
        }else if(goodsInfoAndAttrValueDto.getGameName().contains("和平精英")){
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF10())){
                throw new GlobalException("实名不能为空");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF10()));
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF1());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF2());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF3());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF4());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF5());
        }else if(goodsInfoAndAttrValueDto.getGameName().contains("原神")){
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF20())){
                throw new GlobalException("实名不能为空");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF20()));
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF11());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF17());
        }else if(goodsInfoAndAttrValueDto.getGameName().contains("穿越火线")){
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF3())){
                throw new GlobalException("实名不能为空");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF3()));
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF12());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF13());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF14());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF15());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF16());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF17());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF18());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF19());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF20());
        }else if(goodsInfoAndAttrValueDto.getGameName().contains("光遇")){//=================================未配置游戏属性
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF20())){
                throw new GlobalException("实名不能为空");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF20()));
        }else if(goodsInfoAndAttrValueDto.getGameName().contains("英雄联盟")){
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF1())){
                throw new GlobalException("实名不能为空");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF1()));
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF8());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF9());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF10());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF11());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF12());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF13());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF14());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF15());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF16());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF17());
        }else if(goodsInfoAndAttrValueDto.getGameName().contains("火影忍者")){//=================================未配置游戏属性
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF20())){
                throw new GlobalException("实名不能为空");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF20()));
        }else if(goodsInfoAndAttrValueDto.getGameName().contains("枪战王者")){
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF10())){
                throw new GlobalException("实名不能为空");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF10()));
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF7());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF8());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF11());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF12());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF13());
        }else{
            throw new GlobalException("当前游戏暂不支持");
        }
        List<GameAttribute> gameAttributesss = getGameAttributs(pfIds);
        String des = goodsInfoAndAttrValueDto.getDes();

        des = des.replace("+"," ");
        des = des.replace("☝"," ");
        goodsInfoAndAttrValueDto.setDes(des);

        //填充参数
        Map<String, Object> params = new HashMap<>();
        //商品编号
        params.put("shopcode", goodsInfoAndAttrValueDto.getId().toString());
        //标题
        String title =  "【" +descTitle+"_"+goodsInfoAndAttrValueDto.getId() + "】 " + gameAttribute.getFieldName() + "  " + goodsInfoAndAttrValueDto.getDes();
//        String title =  "1";
        //游戏分类ID，详情见附录
        Integer cateid = (Integer) RegionalCovert.getZjyGameTypeMap(goodsInfoAndAttrValueDto.getGameName());
        //游戏分类ID，详情见附录
        Integer cateid2 = 0;
        if(goodsInfoAndAttrValueDto.getGameName().equals("原神")) {
            cateid2 = (Integer) RegionalCovert.getZjyRegionIdMap(goodsInfoAndAttrValueDto.getGameName(),goodsInfoAndAttrValueDto.getCarrierName());
        }else if(goodsInfoAndAttrValueDto.getGameName().equals("穿越火线")) {
            cateid2 = (Integer) RegionalCovert.getZjyRegionIdMap(goodsInfoAndAttrValueDto.getGameName(),goodsInfoAndAttrValueDto.getGroupName());
        }else if(goodsInfoAndAttrValueDto.getGameName().equals("英雄联盟")) {
            cateid2 = (Integer) RegionalCovert.getZjyRegionIdMap(goodsInfoAndAttrValueDto.getGameName(),goodsInfoAndAttrValueDto.getServerName());
        }else{
            cateid2 = (Integer) RegionalCovert.getZjyRegionIdMap(goodsInfoAndAttrValueDto.getGameName(), goodsInfoAndAttrValueDto.getSystemName() + goodsInfoAndAttrValueDto.getCarrierName());
        }
        if (StringUtils.isNull(cateid)) {
            throw new GlobalException("游戏类型未找到");
        }
        if (StringUtils.isNull(cateid2)) {
            throw new GlobalException("游戏大区未找到");
        }
        //游戏属性或关键字，英文逗号拼接，例如：至臻卡莎,至臻阿卡丽,至臻拉克丝
        String attribute = "";
        if(gameAttributesss.size()>0){
            for(GameAttribute gameAttribute1 : gameAttributesss){
                attribute+=","+gameAttribute1.getFieldName();
            }
        }
        //详情说明，富文本或纯文字说明均可
        String text = "";
        if(StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getDes())) {
            text = goodsInfoAndAttrValueDto.getDes().length()>100?goodsInfoAndAttrValueDto.getDes().substring(0,10):goodsInfoAndAttrValueDto.getDes();
        }
        String logo = goodsInfoAndAttrValueDto.getTitleImg();
        //详情说明，富文本或纯文字说明均可.getTitleImg();
        //图片
        StringBuilder imagesSb = new StringBuilder();
        GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
        goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        goodsInfoImg.setType(Constants.STR_1);
        List<GoodsInfoImg> infoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        if (CollectionUtils.isEmpty(infoImgs)) {
            params.put("images", sa.getTwoOther());
        } else {
            for (GoodsInfoImg img : infoImgs) {
                imagesSb.append(img.getImgUrl()).append(",");
            }
            String images = imagesSb.toString();
            params.put("images", images);
        }

        params.put("title", title);
        params.put("cateid", cateid);
        params.put("cateid2", cateid2);
        params.put("attribute", attribute==null||attribute.equals("")?"":attribute.substring(1));
        BigDecimal bigDecimal = commonApi.addPrice(goodsInfoAndAttrValueDto.getPrice(), sa.getSeleep());
        commonApi.setPrice(bigDecimal,goodsInfoAndAttrValueDto.getId(),sa);
        params.put("money", bigDecimal);

        params.put("text", text);
        params.put("logo", logo);
        params.put("importcode", sa.getOther());
        params.put("importid", sa.getThreeOther());
        return params;
    }

    private List<GameAttribute> getGameAttributs(String ids) {
        return gameAttributeMapper.selectGameAttributeListByIds((Long[]) ConvertUtils.convert(ids.split(","),
                Long.class));
    }

    private String reIds(String allIds, String ids) {
        if (StringUtils.isNotEmpty(ids)) {
            if (StringUtils.isNotEmpty(allIds)) {
                allIds = allIds + "," + ids;
            } else {
                allIds = ids;
            }
        }
        return allIds;
    }

    private Map<String, Object> getSignAndsortMap(List<Map.Entry<String, Object>> entries,SalePartner sa) {


        String key = sa.getSaleKey();
        StringBuilder sb = new StringBuilder();
        HashMap<String, Object> newMap = new HashMap<>();

        for (final Map.Entry<String, Object> m : entries) {
            if (m.getValue() == null) {
                sb.append(m.getKey() + "=" + "1" + "&");
                newMap.put(m.getKey(), "1");
            } else {
                if (StringUtils.isEmpty(m.getValue().toString())) {
                    sb.append(m.getKey() + "=" + "1" + "&");
                    newMap.put(m.getKey(), "1");

                } else {
                    sb.append(m.getKey() + "=" + m.getValue().toString() + "&");
                    newMap.put(m.getKey(), m.getValue());
                }
            }

        }
        sb.append("key=" + key);
        String sign = DigestUtils.md5Hex(sb.toString());
        Map<String, Object> map = MapSort.sortMapByKey(newMap);
        map.put("sign", sign);
        return map;
    }

    public static void main(String[] args) {

        String key = "weacb2c7cfcxd5c31a";
        StringBuilder sb = new StringBuilder();
        HashMap<String, Object> newMap = new HashMap<>();

        Map<String,Object> params = new HashMap<>();

        params.put("cate_id","12");
        params.put("name","1");
        params.put("image","12");
        params.put("arealist","1");

        List<Map.Entry<String, Object>> entries = new MapSort().sortMap(params);

        for (final Map.Entry<String, Object> m : entries) {
            if (m.getValue() == null) {
                sb.append(m.getKey() + "=" + "1" + "&");
                newMap.put(m.getKey(), "1");
            } else {
                if (StringUtils.isEmpty(m.getValue().toString())) {
                    sb.append(m.getKey() + "=" + "1" + "&");
                    newMap.put(m.getKey(), "1");

                } else {
                    sb.append(m.getKey() + "=" + m.getValue().toString() + "&");
                    newMap.put(m.getKey(), m.getValue());
                }
            }

        }
        sb.append("key=" + key);
        String sign = DigestUtils.md5Hex(sb.toString());
        Map<String, Object> map = MapSort.sortMapByKey(newMap);
        map.put("sign", sign);

//        https://www.zhijianyo.com/gshop/tripartite/catelist
        String path = "https://www.milaiyou.com/qyshop/tripartite/catelist";

        String response =   HttpUtils.doPostForm( path, map,null);
        System.out.println(response);

    }
}
